package com.itheima.bigevent.service.impl;

import com.itheima.bigevent.mapper.UserMapper;
import com.itheima.bigevent.pojo.Result;
import com.itheima.bigevent.pojo.User;
import com.itheima.bigevent.service.UserService;
import com.itheima.bigevent.utils.Md5Util;
import com.itheima.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

/**
 * ClassName: UserServiceImpl
 * Package: com.itheima.bigevent.service.impl
 * Description:用户的实现类
 *
 * @Author: Zhang Peiyuan
 * @Create: 2024-08-19-14:59
 * @Version: v1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate rds;
    /**
     * 查询用户
     * @param username
     * @return
     */
    @Override
    public User findByUserName(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public void register(String username, String password) {
        // 加密处理
        String md5String = Md5Util.getMD5String(password);
        // 保存
        userMapper.insertByUsernameAndPassword(username, md5String);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        // 返回存储在ThreadLocalUtil中的map
        Map<String, Object> map = ThreadLocalUtil.get();
        userMapper.updateAvatar(avatarUrl, (Integer)map.get("id"));
    }

    @Override
    public Result<String> updatePassword(Map<String, Object> map) {
        String newPwd = (String) map.get("newPass");
        String oldPwd = (String) map.get("oldPass");
        String rePwd = (String) map.get("rePass");

        if(!StringUtils.hasLength(newPwd) || !StringUtils.hasLength(oldPwd)
                || !StringUtils.hasLength(rePwd)){
            return Result.error("密码不能为空");
        }

        // 校验当前原密码是否正确
        Map<String, Object> token = ThreadLocalUtil.get();
        String username = (String) token.get("username");
        User user = userMapper.selectByUsername(username);

        if(!Md5Util.getMD5String(oldPwd).equals(user.getPassword())){
            return Result.error("原密码错误");
        }
        if(oldPwd.equals(newPwd)){
            return Result.error("新密码不能与原密码相同");
        }
        if(!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }

        userMapper.updatePwd(Md5Util.getMD5String(newPwd), user.getId());
        // 删除旧的token
        rds.opsForValue().getOperations().delete("token_" + map.get("id"));
        // 返回结果
        return Result.success("修改成功");
    }
}
